package com.lanyou.cook.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.repository.KettleSlaveServerRepository;
import com.lanyou.cook.repository.userManagement.UserRepository;
import com.lanyou.esb.entity.ClusterNode;
import com.lanyou.esb.repository.ClusterNodeRepository;
import com.lanyou.esb.web.RestAPI;

@Service
public class KettleSlaveServerService {

	@Autowired
	private CuratorService curatorService;
	
	@Autowired
	private KettleSlaveServerRepository kettleSlaveServerRepository;
	
	@Autowired
	private ClusterNodeRepository clusterNodeRepository;
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private SendEmailService sendEmailService;
	
	@Value("${admin.userCode}")
	private String userCode;
	
	private Map<String, ClusterNode> nodeMap = new HashMap<>();

	public boolean isRunning(long kettleSlaveServerId){
		if (!curatorService.isEnable() || !curatorService.isConnected())
			return false;
		String path = String.format("%s/%d", Constants.ZOOKEPPER_PATH_ACTIVE_JOB_EXECUTORS, kettleSlaveServerId);
		boolean running = false;
		try {
			running = curatorService.getClient().checkExists().forPath(path) != null;
		} catch (Exception e) {
		}
		return running;
	}
	
	//每半小时调度一次
	@Scheduled(cron = "0 0/30 * * * ?")
	public void checkNode(){
		String name = "";
		List<Object[]> allServers = kettleSlaveServerRepository.findAllServer(name);
		List<ClusterNode> clusterNodeLists = new ArrayList<>();
		for (Object[] allServer : allServers) {
			ClusterNode clusterNode = new ClusterNode();
			clusterNode.setId(allServer[0] != null ? (String) allServer[0]: "");
			clusterNode.setName(allServer[1] != null ? (String) allServer[1]: "");
			clusterNode.setIpaddr(allServer[2] != null ? (String) allServer[2] : "");
			if(allServer[3].toString()!=""){
			int port = Integer.valueOf(allServer[3].toString()).intValue();
			clusterNode.setPort(port);
			};
			if(StringUtils.equals(allServer[4].toString(),"0")){
				clusterNode.setType("Kettle");
				long id = Long.valueOf(allServer[0].toString()).longValue();
			boolean running = isRunning(id);
				if(running){
					clusterNode.setRemark("运行中");
				}else{
					clusterNode.setRemark("停止中");
					clusterNodeLists.add(clusterNode);
				}
			}else{
				clusterNode.setType("cookESB");
				if(nodeMap == null || nodeMap.isEmpty()){	//如果缓存为空，将所有数据存入缓存
					if(nodeMap == null){
						nodeMap = new HashMap<>();
					}
					List<ClusterNode> list = clusterNodeRepository.findAll();
					for (ClusterNode clusterNode1 : list) {
						nodeMap.put(clusterNode1.getId(), clusterNode1);
					}
				}
				
				for (ClusterNode clusterNode1 : nodeMap.values()) {
					if(StringUtils.equals(clusterNode1.getName(),clusterNode.getName())){
						String flag = RestAPI.requestByGetMethod(clusterNode1.getIpaddr(), clusterNode1.getPort()+"" ,"NODE");
						if(!StringUtils.equals(flag, "false")){
							clusterNode.setRemark("运行中");
						}else{
							clusterNode.setRemark("停止中");
							clusterNodeLists.add(clusterNode);
						}
					}
				}
			}
		}
		
		if(!clusterNodeLists.isEmpty()){
			User user = userRepository.findByUserCode(userCode);
			try {
				sendEmailService.sendMailBecauseClusterNodeRoot(user, clusterNodeLists, "ClusterNodeNotRunningTemplate");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
